package com.lagou.handler;

import com.lagou.server.UserServerImpl;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class UserServerHandler extends ChannelInboundHandlerAdapter {

  @Override
  public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
    System.out.println("UserServerHandler的channelRegistered方法被调用");
    super.channelRegistered(ctx);
  }

  @Override
  public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
    System.out.println("UserServerHandler的channelUnregistered方法被调用");
    super.channelUnregistered(ctx);
  }

  @Override
  public void channelActive(ChannelHandlerContext ctx) throws Exception {
    System.out.println("UserServerHandler的channelActive方法被调用");
    super.channelActive(ctx);
  }

  @Override
  public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    System.out.println("UserServerHandler的channelInactive方法被调用");
    super.channelInactive(ctx);
  }

  /**
   * @param ctx
   * @param msg
   * @throws Exception
   */
  @Override
  public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    System.out.println("UserServerHandler的channelRead方法被调用");
    // 如何符合约定，则调用本地方法，返回数据
    if (msg.toString().startsWith("UserService")) {
      // msg的构成：UserServer#sayHello#参数
      String result =
          new UserServerImpl().sayHello(msg.toString().substring(msg.toString().lastIndexOf("#")));
      ctx.writeAndFlush(result);
    }
  }

  @Override
  public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
    System.out.println("UserServerHandler的channelReadComplete方法被调用");
    super.channelReadComplete(ctx);
  }

  @Override
  public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    System.out.println("UserServerHandler的userEventTriggered方法被调用");
    super.userEventTriggered(ctx, evt);
  }

  @Override
  public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
    System.out.println("UserServerHandler的channelWritabilityChanged方法被调用");
    super.channelWritabilityChanged(ctx);
  }

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    System.out.println("UserServerHandler的exceptionCaught方法被调用");
    super.exceptionCaught(ctx, cause);
  }
}
